import React, { useState, useEffect } from 'react';
import { Drawer, Form, Input, Select, Button, Row, Col, Cascader } from 'antd';

const { Option } = Select;

interface EquipmentEditDrawerProps {
  open?: boolean;
  visible?: boolean;
  onClose: () => void;
  onSubmit: (values: any) => void;
  equipment?: any;
}

interface ProductOption {
  id: string;
  name: string;
  products?: ProductOption[];
}

interface AreaOption {
  id: string;
  name: string;
  children?: AreaOption[];
}

const EquipmentEditDrawer: React.FC<EquipmentEditDrawerProps> = ({
  open,
  visible,
  onClose,
  onSubmit,
  equipment,
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [gatewayOptions, setGatewayOptions] = useState<any[]>([]);

  // 模拟产品数据
  const mockProductOptions: ProductOption[] = [
    {
      id: '1',
      name: '视频监控系统',
      products: [
        { id: '1-1', name: '网络摄像头' },
        { id: '1-2', name: '硬盘录像机' },
      ],
    },
    {
      id: '2',
      name: '环境监测系统',
      products: [
        { id: '2-1', name: '温度传感器' },
        { id: '2-2', name: '湿度传感器' },
      ],
    },
    {
      id: '3',
      name: '门禁系统',
      products: [
        { id: '3-1', name: '门禁控制器' },
        { id: '3-2', name: '读卡器' },
      ],
    },
  ];

  // 模拟区域数据
  const mockAreaOptions: AreaOption[] = [
    {
      id: '1',
      name: 'A座',
      children: [
        { id: '1-1', name: '1楼' },
        { id: '1-2', name: '2楼' },
        { id: '1-3', name: '3楼' },
      ],
    },
    {
      id: '2',
      name: 'B座',
      children: [
        { id: '2-1', name: '1楼' },
        { id: '2-2', name: '2楼' },
      ],
    },
    {
      id: '3',
      name: 'C座',
      children: [
        { id: '3-1', name: '1楼' },
        { id: '3-2', name: '2楼' },
      ],
    },
  ];

  useEffect(() => {
    const isOpen = open || visible;
    if (isOpen && equipment) {
      // 设置表单数据
      form.setFieldsValue({
        name: equipment.name,
        externalId: equipment.externalId,
        description: equipment.description || '',
        status: equipment.status,
      });
      
      // 模拟根据产品变化更新网关选项
      if (equipment.categoryName) {
        const mockGateways = [
          { gatewayProductId: 'GW001', gatewayProductName: '网关-001' },
          { gatewayProductId: 'GW002', gatewayProductName: '网关-002' },
        ];
        setGatewayOptions(mockGateways);
      }
    }
  }, [open, visible, equipment, form]);

  const handleProductChange = (value: any) => {
    // 模拟根据产品变化更新网关选项
    if (value && value.length > 0) {
      const mockGateways = [
        { gatewayProductId: 'GW001', gatewayProductName: '网关-001' },
        { gatewayProductId: 'GW002', gatewayProductName: '网关-002' },
      ];
      setGatewayOptions(mockGateways);
    } else {
      setGatewayOptions([]);
    }
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      
      // 模拟API调用
      setTimeout(() => {
        onSubmit({ ...equipment, ...values });
        setLoading(false);
      }, 1000);
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  const handleReset = () => {
    if (equipment) {
      form.setFieldsValue({
        name: equipment.name,
        externalId: equipment.externalId,
        description: equipment.description || '',
        status: equipment.status,
      });
    }
  };

  return (
    <Drawer
      title="编辑设备"
      placement="right"
      width={600}
      onClose={onClose}
      open={open || visible}
      footer={
        <div style={{ textAlign: 'right' }}>
          <Button onClick={onClose} style={{ marginRight: 8 }}>
            取消
          </Button>
          <Button onClick={handleReset} style={{ marginRight: 8 }}>
            重置
          </Button>
          <Button type="primary" onClick={handleSubmit} loading={loading}>
            保存
          </Button>
        </div>
      }
    >
      <Form
        form={form}
        layout="vertical"
      >
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="name"
              label="设备名称"
              rules={[{ required: true, message: '请输入设备名称' }]}
            >
              <Input placeholder="请输入设备名称" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="externalId"
              label="设备编号"
              rules={[{ required: true, message: '请输入设备编号' }]}
            >
              <Input placeholder="请输入设备编号" />
            </Form.Item>
          </Col>
        </Row>

        <Form.Item
          name="status"
          label="设备状态"
          rules={[{ required: true, message: '请选择设备状态' }]}
        >
          <Select placeholder="请选择设备状态">
            <Option value="ONLINE">正常</Option>
            <Option value="OFFLINE">离线</Option>
            <Option value="FAILURE">故障</Option>
          </Select>
        </Form.Item>

        <Form.Item
          name="productId"
          label="所属产品"
        >
          <Cascader
            options={mockProductOptions}
            placeholder="请选择所属产品"
            fieldNames={{ label: 'name', value: 'id', children: 'products' }}
            onChange={handleProductChange}
          />
        </Form.Item>

        {gatewayOptions.length > 0 && (
          <Form.Item
            name="gatewayProductId"
            label="归属网关"
          >
            <Select placeholder="请选择归属网关">
              {gatewayOptions.map((item) => (
                <Option key={item.gatewayProductId} value={item.gatewayProductId}>
                  {item.gatewayProductName}
                </Option>
              ))}
            </Select>
          </Form.Item>
        )}

        <Form.Item
          name="areaId"
          label="安装区域"
        >
          <Cascader
            options={mockAreaOptions}
            placeholder="请选择安装区域"
            fieldNames={{ label: 'name', value: 'id', children: 'children' }}
            changeOnSelect
          />
        </Form.Item>

        <Form.Item
          name="description"
          label="设备描述"
        >
          <Input.TextArea
            rows={3}
            placeholder="请输入设备描述"
          />
        </Form.Item>
      </Form>
    </Drawer>
  );
};

export default EquipmentEditDrawer;